//
//  bluetoothMain.m
//  bluetoothTest
//
//  Created by 史沐卉 on 2018/12/14.
//  Copyright © 2018 Facebook. All rights reserved.
//

#import "bluetoothMain.h"
#import <CoreBluetooth/CoreBluetooth.h>

static NSString *const ServiceUUID1 =  @"FFF0";
static NSString *const notiyCharacteristicUUID =  @"FFF1";
static NSString *const readwriteCharacteristicUUID =  @"FFF2";
static NSString *const selfHolographicDevice = @"Bose QuietControl 30";

@interface bluetoothMain ()
/** 系统蓝牙管理对象 */
@property (strong, nonatomic, readwrite) CBCentralManager *manager;
/** 扫描到的设备 */
@property (strong, nonatomic, readwrite) NSMutableArray   *discoverPeripheral;
/** 当前连接设备 */
@property (weak  , nonatomic, readwrite) CBPeripheral     *currentPeripheral;
@end

@implementation bluetoothMain
RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(test) {
  NSLog(@"开始");
}

RCT_EXPORT_METHOD(start)
{
  NSLog(@"BleManager initialized");
  _manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
  if(central.state == CBManagerStatePoweredOn) {
    
    NSLog(@"蓝牙已打开");
    
    //开始扫描设备
    
    //扫描到设备之后会进入
    
    //-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI方法
    
    [_manager scanForPeripheralsWithServices:nil options:nil];
    
  }else{
    
    NSLog(@"蓝牙已关闭");
    
  }
}

// 发现设备回调
-(void)centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
    advertisementData:(NSDictionary<NSString *,id> *)advertisementData
                 RSSI:(NSNumber *)RSSI
{
  NSLog(@"扫描到的蓝牙: %@", peripheral);
  if ([peripheral.name isEqualToString:selfHolographicDevice]) {
    NSLog(@"发现耳机蓝牙: %@", peripheral);
    // 持有设备
    if (![self.discoverPeripheral containsObject:peripheral]) {
      // 使用数组保留外围设备引用
      [self.discoverPeripheral addObject:peripheral];
      [[NSNotificationCenter defaultCenter] postNotificationName:@"BlueToothData" object:nil];
      // 连接设备
      [_manager connectPeripheral:peripheral options:nil];
    }
  }
}

// 扫描到设备的服务后会进入这个方法
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
  NSLog(@"扫描到设备的服务后会进入这个方法");
  if(error){
    NSLog(@"扫描服务错误:%@",[error localizedDescription]);
  }else {
    for (CBService *server in peripheral.services) {
      // 扫描服务的特征
      // 扫描到后会进入
      // - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
      [peripheral discoverCharacteristics:nil forService:server];
      NSLog(@"搜索到了一个服务:%@",server.UUID.UUIDString);
    }
  }
}

@end
